// js/pages/GamePage.js
import BasePage from './BasePage.js';
import TextRenderer from '../utils/TextRenderer.js';
import myFn from '../utils/myFn.js';
import Rectangle from '../ui/Rectangle.js';
import AdvancedComboChart from '../ui/AdvancedComboChart.js';
import IndicatorSettingsModal from '../ui/IndicatorSettingsModal.js';
import ProgressSliderModal from '../ui/ProgressSliderModal.js';

// 提取常量
const UI_CONSTANTS = {
  COLORS: {
    BACKGROUND: '#2C2D4B',
    BACKGROUND_DARK: '#1E1F34',
    BORDER: 'rgba(255, 255, 255, 0.18)',
    TEXT_WHITE: '#ffffff',
    TEXT_YELLOW: '#FFE861',
    TEXT_LIGHT: '#FCF4C4',
    BUY_BUTTON: '#D31B4B',
    SELL_BUTTON: '#05A97A'
  },
  SIZES: {
    TOP_BAR_HEIGHT: 104,
    INDICATOR_BAR_HEIGHT: 46,
    RIGHT_PANEL_WIDTH: 170,
    BOTTOM_BAR_HEIGHT: 114,
    CHART_TOP: 151, // TOP_BAR_HEIGHT + INDICATOR_BAR_HEIGHT
    CHART_BOTTOM: 636,
    CHART_LEFT: 0,
    CHART_RIGHT: 1454
  },
  BUTTONS: {
    CLOSE: { X: 30, Y: 12, WIDTH: 40, HEIGHT: 80 },
    BUY: { X: 64, Y: 650, WIDTH: 239, HEIGHT: 88 },
    SELL: { X: 298, Y: 650, WIDTH: 239, HEIGHT: 88 },
    CHANGE_STOCK: { X: 1116, Y: 658, WIDTH: 171, HEIGHT: 72 },
    START: { X: 1322, Y: 650, WIDTH: 239, HEIGHT: 88 },
    PASS: { X: 1290, Y: 650, WIDTH: 239, HEIGHT: 88 },
    SETTINGS: { X: 0, Y: 550, WIDTH: 50, HEIGHT: 50 }
  },
  FONT_SIZES: {
    NORMAL: 28,
    SMALL: 20,
    BUTTON: 32,
    INDICATOR: 24,
    HEADER: 32
  },
  POSITIONS: {
    ASSET_PANEL: { X: 106, Y: 104, WIDTH: 320, HEIGHT: 104 },
    STOCK_PANEL: { X: 426, Y: 104, WIDTH: 320, HEIGHT: 104 },
    REVENUE_PANEL: { X: 746, Y: 104, WIDTH: 320, HEIGHT: 104 },
    SHARE_TEXT: { X: 1100, Y: 40 },
    SHARE_ICON: { X: 1340, Y: 22, WIDTH: 58, HEIGHT: 58 },
    INDICATOR_BAR: { Y: 120 },
    RIGHT_PANEL: { TOP: 170, SPACING: 100, WIDTH: 85 }
  }
};

export default class GamePage extends BasePage {
  constructor(canvas, ctx, pageManager, resourceManager, screenAdapter, api, userManager) {
    super(canvas, ctx, pageManager, resourceManager, screenAdapter);
    this.api = api;
    this.userManager = userManager;
    this.textRenderer = new TextRenderer(ctx, screenAdapter);

    // 游戏状态
    this.gameState = {
      selectedIndicator: 'DEAL',
      isBuyOperation: false,
      isSellOperation: false,
      isSetOperation: false,
      isGameOver: false,
      isBuy: false,
      isStart: false,
      isOver: false
    };

    // UI组件
    this.uiComponents = {
      chart: null,
      buyDialog: null,
      sellDialog: null,
      setDialog: null
    };

    // 数据
    this.stockList = [];
    this.userStock = {
      balance: 0,
      balance_ratio: 100,
      game_id: 0,
      revenue: 0,
      revenue_ratio: 0,
      stock: 0,
      stock_ratio: 0
    };
    this.todayStock = {
      pct_chg: 0,
      turnover_rate: 0
    };
    this.visibleKLineIndicators = ['MA5', 'MA10', 'MA20', 'MA30'];
    this.isInitialized = false;
  }

  onInit() {
    return Promise.resolve();
  }

  /**
   * 页面初始化方法
   */
  async initialize() {
    try {
      this.resetGameState();
      await this.initializeUI();
      await this.fetchGameData();
      this.isInitialized = true;
    } catch (error) {
      console.error('游戏页面初始化失败:', error);
      throw error;
    }
  }

  /**
   * 重置游戏状态
   */
  resetGameState() {
    this.gameState = {
      selectedIndicator: 'DEAL',
      isBuyOperation: false,
      isSellOperation: false,
      isSetOperation: false,
      isGameOver: false,
      isBuy: false,
      isStart: false,
      isOver: false
    };
  }

  /**
   * 初始化UI组件
   */
  initializeUI() {
    this.initializeChart();
    this.initializeDialogs();
  }

  /**
   * 初始化图表组件
   */
  initializeChart() {
    this.uiComponents.chart = new AdvancedComboChart({
      showYAxisLabels: false,
      dataFields: {
        date: 'trade_date',
        open: 'open_hfq',
        close: 'close_hfq',
        high: 'high_hfq',
        low: 'low_hfq',
        volume: 'vol',
        macd: 'macd_hfq',
        kdj: 'kdj_hfq',
        boll: 'boll_lower_hfq',
      }
    }, this.textRenderer);
  }

  /**
   * 初始化对话框组件
   */
  initializeDialogs() {
    // 设置对话框
    this.uiComponents.setDialog = new IndicatorSettingsModal({
      canvasWidth: this.screenAdapter.DESIGN_WIDTH,
      canvasHeight: this.screenAdapter.DESIGN_HEIGHT,
      onBtnClick: (value) => {
        this.gameState.isSetOperation = false;
        this.uiComponents.chart.setVisibleIndicators(value);
        this.visibleKLineIndicators = value;
        console.log('当前所选指标:', value);
      },
      onClose: () => {
        this.gameState.isSetOperation = false;
        console.log('设置弹窗关闭');
      }
    }, this.textRenderer, this.screenAdapter, this.resourceManager);

    // 买入对话框
    this.uiComponents.buyDialog = new ProgressSliderModal({
      canvasWidth: this.screenAdapter.DESIGN_WIDTH,
      canvasHeight: this.screenAdapter.DESIGN_HEIGHT,
      type: 'BUY',
      color: UI_CONSTANTS.COLORS.BUY_BUTTON,
      onBtnClick: (value) => {
        console.log('当前买入数量:', value);
        this.executeTrade('BUY', value);
      },
      onClose: () => {
        this.gameState.isBuyOperation = false;
        console.log('买入弹窗关闭');
      }
    }, this.textRenderer, this.screenAdapter, this.resourceManager);

    // 卖出对话框
    this.uiComponents.sellDialog = new ProgressSliderModal({
      canvasWidth: this.screenAdapter.DESIGN_WIDTH,
      canvasHeight: this.screenAdapter.DESIGN_HEIGHT,
      type: 'SELL',
      color: UI_CONSTANTS.COLORS.SELL_BUTTON,
      onBtnClick: (value) => {
        console.log('当前卖出数量:', value);
        this.executeTrade('SELL', value);
      },
      onClose: () => {
        this.gameState.isSellOperation = false;
        console.log('卖出弹窗关闭');
      }
    }, this.textRenderer, this.screenAdapter, this.resourceManager);
  }

  /**
   * 获取游戏数据
   */
  async fetchGameData() {
    try {
      await this.getStockList();
      this.userStock.balance = wx.getStorageSync('userBalance') || 0;
    } catch (error) {
      console.error('获取游戏数据失败:', error);
    }
  }

  /**
   * 渲染页面
   */
  render() {
    if (!this.isInitialized) return;

    this.renderBackground();
    this.renderTopSection();
    this.renderRightSection();
    this.renderBottomSection();
    this.renderChart();
    this.renderDialogs();
  }

  /**
   * 渲染背景
   */
  renderBackground() {
    this.ctx.fillStyle = UI_CONSTANTS.COLORS.BACKGROUND;
    this.ctx.fillRect(0, 0, this.screenAdapter.DESIGN_WIDTH, this.screenAdapter.DESIGN_HEIGHT);
  }

  /**
   * 渲染顶部区域
   */
  renderTopSection() {
    this.renderTopBar();
    this.renderIndicatorBar();
  }

  /**
   * 渲染顶部状态栏
   */
  renderTopBar() {
    // 背景和边框
    this.ctx.fillStyle = UI_CONSTANTS.COLORS.BACKGROUND;
    this.ctx.fillRect(0, 0, this.screenAdapter.DESIGN_WIDTH, UI_CONSTANTS.SIZES.TOP_BAR_HEIGHT);
    this.drawSingleSideBorder(0, 0, this.screenAdapter.DESIGN_WIDTH, UI_CONSTANTS.SIZES.TOP_BAR_HEIGHT, 'bottom', UI_CONSTANTS.COLORS.BORDER, 2);

    // 关闭按钮
    this.textRenderer.drawText('×', UI_CONSTANTS.BUTTONS.CLOSE.X, UI_CONSTANTS.BUTTONS.CLOSE.Y, `80px ${this.textRenderer.systemFont}`, UI_CONSTANTS.COLORS.TEXT_WHITE, 'left', 'top');

    // 渲染资产面板
    this.renderAssetPanels();

    // 渲染分享区域
    if (!this.gameState.isStart) {
      this.renderShareSection();
    }
  }

  /**
   * 渲染资产面板
   */
  renderAssetPanels() {
    // 绘制资产面板背景
    Rectangle.drawTrapezoidWithSideEdges(this.ctx, 106, 104, 320, 320, 104, 20, {
      fillColor: '#1E1F34',
      strokeColor: "rgba(255, 255, 255, 0.11)",
      lineWidth: 2
    });

    // 绘制"资产"信息
    this.textRenderer.drawText('资产', 140, 20, `28px ${this.textRenderer.systemFont}`, '#ffffff', 'left', 'top');
    this.textRenderer.drawText(this.userStock.balance, 410, 20, `28px ${this.textRenderer.systemFont}`, '#ffffff', 'right', 'top');
    this.textRenderer.drawText('占比', 140, 70, `20px ${this.textRenderer.systemFont}`, '#ffffff', 'left', 'top');
    this.textRenderer.drawText(`${this.userStock.balance_ratio}%`, 410, 70, `20px ${this.textRenderer.systemFont}`, '#ffffff', 'right', 'top');

    if (this.gameState.isBuy && this.gameState.isStart) {
      // 绘制股票面板背景
      Rectangle.drawTrapezoidWithSideEdges(this.ctx, 426, 104, 320, 320, 104, 20, {
        fillColor: '#1E1F34',
        strokeColor: "rgba(255, 255, 255, 0.11)",
        lineWidth: 2
      });

      // 绘制"股票"信息
      this.textRenderer.drawText('股票', 460, 20, `28px ${this.textRenderer.systemFont}`, '#ffffff', 'left', 'top');
      this.textRenderer.drawText(this.userStock.stock, 730, 20, `28px ${this.textRenderer.systemFont}`, '#ffffff', 'right', 'top');
      this.textRenderer.drawText('占比', 460, 70, `20px ${this.textRenderer.systemFont}`, '#ffffff', 'left', 'top');
      this.textRenderer.drawText(`${this.userStock.stock_ratio}%`, 730, 70, `20px ${this.textRenderer.systemFont}`, '#ffffff', 'right', 'top');

      // 绘制收益面板背景
      Rectangle.drawTrapezoidWithSideEdges(this.ctx, 746, 104, 320, 320, 104, 20, {
        fillColor: '#1E1F34',
        strokeColor: "rgba(255, 255, 255, 0.11)",
        lineWidth: 2
      });

      // 绘制"收益"信息
      this.textRenderer.drawText('收益', 780, 20, `28px ${this.textRenderer.systemFont}`, '#ffffff', 'left', 'top');
      this.textRenderer.drawText(this.userStock.revenue, 1050, 20, `28px ${this.textRenderer.systemFont}`, '#ffffff', 'right', 'top');
      this.textRenderer.drawText('占比', 780, 70, `20px ${this.textRenderer.systemFont}`, '#ffffff', 'left', 'top');
      this.textRenderer.drawText(`${this.userStock.revenue_ratio}%`, 1050, 70, `20px ${this.textRenderer.systemFont}`, '#ffffff', 'right', 'top');
    }

    // 渲染分享区域
    if (!this.gameState.isStart) {
      this.renderShareSection();
    }
  }

  /**
   * 渲染分享区域
   */
  renderShareSection() {
    // 分享文本
    this.textRenderer.drawText('分享领资金：5/5', UI_CONSTANTS.POSITIONS.SHARE_TEXT.X, UI_CONSTANTS.POSITIONS.SHARE_TEXT.Y, `${UI_CONSTANTS.FONT_SIZES.NORMAL}px ${this.textRenderer.systemFont}`, UI_CONSTANTS.COLORS.TEXT_WHITE, 'left', 'top');

    // 分享图标
    const shareIcon = this.resourceManager.getImage('shareIcon');
    if (shareIcon) {
      this.ctx.drawImage(shareIcon, UI_CONSTANTS.POSITIONS.SHARE_ICON.X, UI_CONSTANTS.POSITIONS.SHARE_ICON.Y, UI_CONSTANTS.POSITIONS.SHARE_ICON.WIDTH, UI_CONSTANTS.POSITIONS.SHARE_ICON.HEIGHT);
    }
  }

  /**
   * 渲染指标栏
   */
  renderIndicatorBar() {
    // 背景 - 修复：使用正确的Y坐标
    this.ctx.fillStyle = '#1e1e1e';
    this.ctx.fillRect(0, 105, this.screenAdapter.DESIGN_WIDTH, 46);

    const indicatorY = 120

    // 指标配置：包含每个指标的颜色和基础位置
    const indicatorConfig = {
      'MA5': { color: '#FFA726', baseX: 76 },
      'MA10': { color: '#66BB6A', baseX: 168 },
      'MA20': { color: '#42A5F5', baseX: 254 },
      'MA30': { color: '#EC407A', baseX: 350 },
      'MA60': { color: '#AB47BC', baseX: 448 },
      'MA90': { color: '#5C6BC0', baseX: 548 },
      'MA250': { color: '#26C6DA', baseX: 648 }
    };

    // 根据用户选择的指标动态渲染
    if (this.visibleKLineIndicators && this.visibleKLineIndicators.length > 0) {
      // 计算指标间距：基于第一个和最后一个指标的位置
      const firstIndicator = this.visibleKLineIndicators[0];
      const lastIndicator = this.visibleKLineIndicators[this.visibleKLineIndicators.length - 1];
      const firstX = indicatorConfig[firstIndicator]?.baseX || 76;
      const lastX = indicatorConfig[lastIndicator]?.baseX || 648;

      // 如果只有一个指标，使用默认间距
      const spacing = this.visibleKLineIndicators.length > 1
        ? (lastX - firstX) / (this.visibleKLineIndicators.length - 1)
        : 0;

      // 渲染每个选中的指标
      this.visibleKLineIndicators.forEach((indicator, index) => {
        const config = indicatorConfig[indicator];
        if (config) {
          // 计算动态X坐标
          const x = firstX + index * spacing;

          // 渲染指标文本
          this.textRenderer.drawText(
            indicator,
            x,
            indicatorY,
            `24px ${this.textRenderer.systemFont}`,
            config.color,
            'center',
            'top'
          );
        }
      });
    }

    // 股票信息
    if (this.gameState.isStart) {
      this.textRenderer.drawText(`涨幅：${this.todayStock.pct_chg}`, 1150, indicatorY, `24px ${this.textRenderer.systemFont}`, '#FCF4C4', 'center', 'top');
      this.textRenderer.drawText(`换手：${this.todayStock.turnover_rate}`, 1350, indicatorY, `24px ${this.textRenderer.systemFont}`, '#FCF4C4', 'center', 'top');
    }
  }

  /**
   * 渲染右侧指标栏
   */
  renderRightSection() {
    // 背景
    this.ctx.fillStyle = UI_CONSTANTS.COLORS.BACKGROUND;
    this.ctx.fillRect(this.screenAdapter.DESIGN_WIDTH - UI_CONSTANTS.SIZES.RIGHT_PANEL_WIDTH, 106, UI_CONSTANTS.SIZES.RIGHT_PANEL_WIDTH, 536);
    this.drawSingleSideBorder(this.screenAdapter.DESIGN_WIDTH - UI_CONSTANTS.SIZES.RIGHT_PANEL_WIDTH, 106, UI_CONSTANTS.SIZES.RIGHT_PANEL_WIDTH, 536, 'left', UI_CONSTANTS.COLORS.BORDER, 2);

    // 修复：使用原始的坐标和渲染方式
    const fontColor = '#fff';
    const activeFontColor = '#FFE861';
    const rightWidth = 85;
    const rightTop = 170;
    const rightSpacing = 100;

    // 绘制"成交量"指标
    this.textRenderer.drawText('成交量', this.screenAdapter.DESIGN_WIDTH - rightWidth, rightTop, `32px ${this.textRenderer.systemFont}`, this.gameState.selectedIndicator == 'DEAL' ? activeFontColor : fontColor, 'center', 'top');

    // 绘制"MACD"指标
    this.textRenderer.drawText('MACD', this.screenAdapter.DESIGN_WIDTH - rightWidth, rightTop + rightSpacing, `32px ${this.textRenderer.systemFont}`, this.gameState.selectedIndicator == 'MACD' ? activeFontColor : fontColor, 'center', 'top');

    // 绘制"KDJ"指标
    this.textRenderer.drawText('KDJ', this.screenAdapter.DESIGN_WIDTH - rightWidth, rightTop + rightSpacing * 2, `32px ${this.textRenderer.systemFont}`, this.gameState.selectedIndicator == 'KDJ' ? activeFontColor : fontColor, 'center', 'top');

    // 绘制"BOLL"指标
    this.textRenderer.drawText('BOLL', this.screenAdapter.DESIGN_WIDTH - rightWidth, rightTop + rightSpacing * 3, `32px ${this.textRenderer.systemFont}`, this.gameState.selectedIndicator == 'BOLL' ? activeFontColor : fontColor, 'center', 'top');

    // 绘制设置按钮
    const setIcon = this.resourceManager.getImage('setIcon');
    if (setIcon) {
      this.ctx.drawImage(setIcon, this.screenAdapter.DESIGN_WIDTH - rightWidth - 25, 550, 50, 50);
    }
  }

  /**
   * 渲染底部操作栏
   */
  renderBottomSection() {
    // 背景
    this.ctx.fillStyle = UI_CONSTANTS.COLORS.BACKGROUND;
    this.ctx.fillRect(0, 636, this.screenAdapter.DESIGN_WIDTH, UI_CONSTANTS.SIZES.BOTTOM_BAR_HEIGHT);
    this.drawSingleSideBorder(0, 636, this.screenAdapter.DESIGN_WIDTH, UI_CONSTANTS.SIZES.BOTTOM_BAR_HEIGHT, 'top', UI_CONSTANTS.COLORS.BORDER, 2);

    // 买入按钮
    this.renderButton(UI_CONSTANTS.BUTTONS.BUY, 'buyIcon', '买');

    // 卖出按钮
    this.renderButton(UI_CONSTANTS.BUTTONS.SELL, 'sellIcon', '卖');

    if (this.gameState.isStart) {
      // 过按钮
      this.renderButton(UI_CONSTANTS.BUTTONS.PASS, 'againIcon', '过');

      // K线信息
      this.textRenderer.drawText(
        `K线：${this.stockList.length - this.uiComponents.chart.getDisplayedDataCount()}`,
        this.screenAdapter.DESIGN_WIDTH / 2,
        680,
        `${UI_CONSTANTS.FONT_SIZES.INDICATOR}px ${this.textRenderer.systemFont}`,
        UI_CONSTANTS.COLORS.TEXT_LIGHT,
        'center',
        'top'
      );
    } else {
      // 换股按钮
      this.renderButton(UI_CONSTANTS.BUTTONS.CHANGE_STOCK, 'changeDiceIcon', '换股');

      // 开始按钮
      this.renderButton(UI_CONSTANTS.BUTTONS.START, 'startIcon', '开始');
    }
  }

  /**
   * 渲染按钮
   */
  renderButton(buttonConfig, imageKey, text) {
    const buttonImage = this.resourceManager.getImage(imageKey);
    if (buttonImage) {
      this.ctx.drawImage(buttonImage, buttonConfig.X, buttonConfig.Y, buttonConfig.WIDTH, buttonConfig.HEIGHT);
    }

    this.textRenderer.drawText(
      text,
      buttonConfig.X + buttonConfig.WIDTH / 2,
      text == '换股' ? buttonConfig.Y + 20 : buttonConfig.Y + 30,
      `${UI_CONSTANTS.FONT_SIZES.BUTTON}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT_WHITE,
      'center',
      'top'
    );
  }

  /**
   * 渲染图表
   */
  renderChart() {
    if (this.uiComponents.chart) {
      this.uiComponents.chart.draw(this.ctx);
    }
  }

  /**
   * 渲染对话框
   */
  renderDialogs() {
    if (this.uiComponents.buyDialog) {
      this.uiComponents.buyDialog.draw(this.ctx);
    }
    if (this.uiComponents.sellDialog) {
      this.uiComponents.sellDialog.draw(this.ctx);
    }
    if (this.uiComponents.setDialog) {
      this.uiComponents.setDialog.draw(this.ctx);
    }
  }

  /**
   * 绘制单边边框
   */
  drawSingleSideBorder(x, y, width, height, side, color, lineWidthRpx) {
    const rpxToPixelRatio = this.screenAdapter.DESIGN_WIDTH / 750;
    const lineWidth = lineWidthRpx * rpxToPixelRatio;

    this.ctx.strokeStyle = color;
    this.ctx.lineWidth = lineWidth;
    this.ctx.beginPath();

    switch (side) {
      case 'top':
        this.ctx.moveTo(x, y);
        this.ctx.lineTo(x + width, y);
        break;
      case 'bottom':
        this.ctx.moveTo(x, y + height);
        this.ctx.lineTo(x + width, y + height);
        break;
      case 'left':
        this.ctx.moveTo(x, y);
        this.ctx.lineTo(x, y + height);
        break;
      case 'right':
        this.ctx.moveTo(x + width, y);
        this.ctx.lineTo(x + width, y + height);
        break;
      default:
        console.error('Invalid side specified. Use "top", "bottom", "left", or "right".');
        return;
    }

    this.ctx.stroke();
  }

  /**
   * 处理触摸开始事件
   */
  handleTouchStart(event) {
    const touch = event.touches[0];
    const logicPoint = this.screenAdapter.screenToLogic(touch.clientX, touch.clientY);

    // 处理图表触摸
    if (this.isChartArea(logicPoint)) {
      this.uiComponents.chart.handleTouchStart(logicPoint.x, logicPoint.y);
    }

    // 处理对话框触摸
    if (this.gameState.isBuyOperation) {
      this.uiComponents.buyDialog.handleTouchStart(logicPoint.x, logicPoint.y);
    } else if (this.gameState.isSellOperation) {
      this.uiComponents.sellDialog.handleTouchStart(logicPoint.x, logicPoint.y);
    }
  }

  /**
   * 处理触摸结束事件
   */
  handleTouchEnd(event) {
    const touch = event.changedTouches[0];
    const logicPoint = this.screenAdapter.screenToLogic(touch.clientX, touch.clientY);

    // 处理关闭按钮
    if (this.isCloseButtonClicked(logicPoint)) {
      if (!this.isAnyDialogOpen()) {
        this.pageManager.showPage('home');
      }
      return;
    }

    // 处理对话框触摸
    if (this.gameState.isBuyOperation) {
      this.uiComponents.buyDialog.handleTouchEnd(logicPoint.x, logicPoint.y);
    } else if (this.gameState.isSellOperation) {
      this.uiComponents.sellDialog.handleTouchEnd(logicPoint.x, logicPoint.y);
    } else if (this.gameState.isSetOperation) {
      this.uiComponents.setDialog.handleTouch(logicPoint.x, logicPoint.y);
    } else {
      // 处理底部按钮点击
      if (this.isBottomBarArea(logicPoint)) {
        this.handleBottomButtonClick(logicPoint);
      }

      // 处理图表触摸
      if (this.isChartArea(logicPoint)) {
        this.uiComponents.chart.handleTouchEnd(logicPoint.x, logicPoint.y);
      }

      // 处理右侧菜单点击 - 修复：使用原始的坐标判断
      if (logicPoint.x >= 1460 && logicPoint.x <= 1620) {
        //点击成交量菜单
        if (logicPoint.y >= 160 && logicPoint.y <= 215) {
          this.gameState.selectedIndicator = 'DEAL';
          this.uiComponents.chart.clearFloatingLabel();
          this.uiComponents.chart.setBarChartIndicator('volume');
        }
        //点击MACD菜单
        else if (logicPoint.y >= 260 && logicPoint.y <= 315) {
          this.gameState.selectedIndicator = 'MACD';
          this.uiComponents.chart.clearFloatingLabel();
          this.uiComponents.chart.setBarChartIndicator('macd');
        }
        //点击KDJ菜单
        else if (logicPoint.y >= 360 && logicPoint.y <= 415) {
          this.gameState.selectedIndicator = 'KDJ';
          this.uiComponents.chart.clearFloatingLabel();
          this.uiComponents.chart.setBarChartIndicator('kdj');
        }
        //点击BOLL菜单
        else if (logicPoint.y >= 460 && logicPoint.y <= 515) {
          this.gameState.selectedIndicator = 'BOLL';
          this.uiComponents.chart.clearFloatingLabel();
          this.uiComponents.chart.setBarChartIndicator('boll');
        }
        //点击设置菜单
        else if (logicPoint.y >= 560 && logicPoint.y <= 620) {
          this.gameState.isSetOperation = true;
          this.uiComponents.chart.clearFloatingLabel();
          this.uiComponents.setDialog.show(this.visibleKLineIndicators);
        }
      }
    }
  }

  /**
   * 处理触摸移动事件
   */
  handleTouchMove(event) {
    const touch = event.touches[0];
    const logicPoint = this.screenAdapter.screenToLogic(touch.clientX, touch.clientY);

    if (this.gameState.isBuyOperation) {
      this.uiComponents.buyDialog.handleTouchMove(logicPoint.x, logicPoint.y);
    } else if (this.gameState.isSellOperation) {
      this.uiComponents.sellDialog.handleTouchMove(logicPoint.x, logicPoint.y);
    } else if (this.gameState.isSetOperation) {
      this.uiComponents.setDialog.handleTouchMove(logicPoint.x, logicPoint.y);
    } else {
      this.uiComponents.chart.handleTouchMove(logicPoint.x, logicPoint.y);
    }
  }

  /**
   * 检查是否点击了关闭按钮
   */
  isCloseButtonClicked(point) {
    const btn = UI_CONSTANTS.BUTTONS.CLOSE;
    return point.x >= btn.X &&
      point.x <= btn.X + btn.WIDTH &&
      point.y >= btn.Y &&
      point.y <= btn.Y + btn.HEIGHT;
  }

  /**
   * 检查是否有对话框打开
   */
  isAnyDialogOpen() {
    return this.gameState.isBuyOperation ||
      this.gameState.isSellOperation ||
      this.gameState.isSetOperation;
  }

  /**
   * 检查是否在图表区域
   */
  isChartArea(point) {
    return point.x >= UI_CONSTANTS.SIZES.CHART_LEFT &&
      point.x <= UI_CONSTANTS.SIZES.CHART_RIGHT &&
      point.y >= UI_CONSTANTS.SIZES.CHART_TOP &&
      point.y <= UI_CONSTANTS.SIZES.CHART_BOTTOM;
  }

  /**
   * 检查是否在底部操作栏区域
   */
  isBottomBarArea(point) {
    return point.y >= 658 && point.y <= 740;
  }

  /**
   * 处理底部按钮点击
   */
  handleBottomButtonClick(point) {
    // 买入按钮
    if (this.isButtonClicked(point, UI_CONSTANTS.BUTTONS.BUY)) {
      this.handleBuyButtonClick();
      return;
    }

    // 卖出按钮
    if (this.isButtonClicked(point, UI_CONSTANTS.BUTTONS.SELL)) {
      this.handleSellButtonClick();
      return;
    }

    // 换股按钮
    if (this.isButtonClicked(point, UI_CONSTANTS.BUTTONS.CHANGE_STOCK)) {
      this.handleChangeStockButtonClick();
      return;
    }

    // 开始按钮
    if (this.isButtonClicked(point, UI_CONSTANTS.BUTTONS.START)) {
      this.handleStartButtonClick();
      return;
    }

    // 过按钮
    if (this.isButtonClicked(point, UI_CONSTANTS.BUTTONS.PASS)) {
      this.handlePassButtonClick();
    }
  }

  /**
   * 检查按钮是否被点击
   */
  isButtonClicked(point, button) {
    return point.x >= button.X &&
      point.x <= button.X + button.WIDTH &&
      point.y >= button.Y &&
      point.y <= button.Y + button.HEIGHT;
  }

  /**
   * 处理买入按钮点击
   */
  handleBuyButtonClick() {
    if (!this.gameState.isStart) {
      myFn.showToast('请先开始游戏');
      return;
    }

    if (this.gameState.isOver) {
      myFn.showToast('游戏已结束，请返回重新开始');
      return;
    }

    this.uiComponents.chart.clearFloatingLabel();
    this.gameState.isBuyOperation = true;

    const stock = this.getTodayStockData();
    const maxShares = Math.trunc(this.userStock.balance / (stock.open_hfq * 100));
    this.uiComponents.buyDialog.show(maxShares, 1);
  }

  /**
   * 处理卖出按钮点击
   */
  handleSellButtonClick() {
    if (!this.gameState.isStart) {
      myFn.showToast('请先开始游戏');
      return;
    }

    if (this.gameState.isOver) {
      myFn.showToast('游戏已结束，请返回重新开始');
      return;
    }

    if (!this.gameState.isBuy) {
      myFn.showToast('请先买入股票');
      return;
    }

    this.uiComponents.chart.clearFloatingLabel();
    this.gameState.isSellOperation = true;

    const stock = this.getTodayStockData();
    // console.log('stock=', stock)
    // console.log('userStock.stock=' + this.userStock.stock)

    const maxShares = Math.trunc(Math.min(stock.vol, this.userStock.stock));
    this.uiComponents.sellDialog.show(maxShares, 1);
  }

  /**
   * 处理换股按钮点击
   */
  handleChangeStockButtonClick() {
    if (this.gameState.isStart) return;

    this.getStockList();
  }

  /**
   * 处理开始按钮点击
   */
  handleStartButtonClick() {
    if (!this.gameState.isStart) {
      this.gameState.isStart = true;
    }
    //刷新用户数据
    this.userManager.refreshUserData()

    this.uiComponents.chart.clearFloatingLabel();
    this.isAnotherOne();
  }

  /**
   * 处理过按钮点击
   */
  handlePassButtonClick() {
    this.uiComponents.chart.clearFloatingLabel();
    this.isAnotherOne();
  }

  /**
   * 执行买卖操作
   */
  async executeTrade(type, position) {
    try {
      const stock = this.getTodayStockData();

      const response = await this.api.game.BuyOrSell({
        type: type,
        trade_date: stock.trade_date,
        position: position
      });

      this.userStock = response.data;
      this.gameState.isBuy = true;

      if (type === 'BUY') {
        myFn.showToast('买入成功', 'success');
        this.gameState.isBuyOperation = false;
      } else if (type === 'SELL') {
        myFn.showToast('卖出成功', 'success');
        this.gameState.isSellOperation = false;
      }

      this.isAnotherOne();
    } catch (error) {
      console.error('交易失败:', error);
      //myFn.showToast('交易失败，请重试');
      myFn.showToast(error);
    }
  }

  /**
   * 获取当日股票数据
   */
  getTodayStockData() {
    const index = this.uiComponents.chart.getDisplayedDataCount();
    return this.stockList[index];
  }

  /**
   * 游戏结束处理
   */
  async gameOver() {
    try {
      const response = await this.api.game.gameOver({
        game_id: this.userStock.game_id
      });

      wx.setStorageSync('gameData', response.data);
      this.pageManager.showPage('settlement');
    } catch (error) {
      console.error('游戏结束处理失败:', error);
      myFn.showToast('游戏结束处理失败，请重试');
    }
  }

  /**
   * 获取股票列表
   */
  async getStockList() {
    try {
      const response = await this.api.game.begin();
      this.stockList = response.data;
      this.uiComponents.chart.updateData(response.data);
      this.todayStock = this.stockList[49];
    } catch (error) {
      console.error('获取股票列表失败:', error);
      myFn.showToast('获取股票数据失败，请重试');
    }
  }

  /**
   * 处理下一根K线
   */
  isAnotherOne() {
    if (this.uiComponents.chart.getDisplayedDataCount() >= this.stockList.length) {
      this.gameState.isOver = true;

      if (this.gameState.isBuy) {
        this.gameOver();
      } else {
        myFn.showToast('游戏已结束，您未购买任何股票，请返回重新开始');
      }
    } else {
      const nextDataPoint = this.uiComponents.chart.allData[this.uiComponents.chart.displayedData.length];
      this.uiComponents.chart.appendData(nextDataPoint);
      this.todayStock = nextDataPoint;
    }
  }

  /**
   * 获取选中的指标
   */
  getSelectIndicator(indicator) {
    console.log('-getSelectIndicator-');
    this.visibleKLineIndicators = indicator;
    this.uiComponents.chart.setVisibleIndicators(indicator);
  }

  /**
   * 显示结果（预留方法）
   */
  revealResult() {
    // 预留方法，用于显示游戏结果
  }
}
